<template>
  <div class="asset-manage-makerpn">
    <Form
      :label-width="100"
      :model="formData"
      :rules="formRule"
      ref="formValidate"
      inline
      class="asset-manage-makerpn-info"
    >
      <div class="ivu-table ivu-table-default  ivu-table-noborder">
        <div class="ivu-table-body table-border-none">
          <table cellspacing="0" cellpadding="0" border="0" style="width: 100%;">
            <tbody class="ivu-table-tbody">
              <tr class="ivu-table-row">
                <td colspan="2">
                  <div class="ivu-table-cell">
                    <h3 class="title"><span class="title-icon"></span> <span>编码信息</span></h3>
                  </div>
                </td>
              </tr>
              <tr class="ivu-table-row">
                <td class="none-border">
                  <div class="ivu-table-cell">
                    <FormItem prop="purchaseType" label="采购类型：">
                      <Select v-model="formData.purchaseType" transfer placeholder="请选择" class="input-width">
                        <Option v-for="item in purchaseTypeData" :value="item.value" :key="item.value">{{
                          item.label
                        }}</Option>
                      </Select>
                      <!-- <Input class="input-width" placeholder="填写不超过32个字符，非特殊编码" /> -->
                    </FormItem>
                  </div>
                </td>
                <td class="none-border">
                  <div class="ivu-table-cell">
                    <FormItem prop="purchaseTime" label="采购时间：">
                      <DatePicker
                        v-model="formData.purchaseTime"
                        transfer
                        :editable="false"
                        :clearable="false"
                        type="month"
                        placeholder="请选择"
                        class="input-width"
                      ></DatePicker>
                    </FormItem>
                  </div>
                </td>
              </tr>
              <tr class="ivu-table-row">
                <td class="none-border">
                  <div class="ivu-table-cell">
                    <FormItem prop="pnCode" label="机台产品：">
                      <Select
                        v-model="formData.pnCode"
                        :loading="loading"
                        remote
                        :remote-method="handleRemoteMethod"
                        transfer
                        filterable
                        placeholder="请选择"
                        class="input-width"
                      >
                        <Option v-for="(item, index) in pnCodeData" :value="item.pnCode" :key="index">{{
                          item.pnCode
                        }}</Option>
                      </Select>
                    </FormItem>
                  </div>
                </td>
                <td class="none-border">
                  <div class="ivu-table-cell">
                    <FormItem prop="purchaseAmount" label="采购数量：">
                      <Select v-model="formData.purchaseAmount" transfer placeholder="请选择" class="input-width">
                        <Option v-for="item in purchaseAmountData" :value="item.value" :key="item.value">{{
                          item.label
                        }}</Option>
                      </Select>
                    </FormItem>
                  </div>
                </td>
              </tr>

              <tr class="ivu-table-row">
                <td></td>
                <td class="none-border">
                  <div class="ivu-table-cell">
                    <!-- <FormItem > -->
                    <!-- <Row type="flex" justify="end"> -->
                    <FormItem>
                      <Row type="flex" justify="end" class="input-width">
                        <Button @click="handleGenerateCode" type="primary">生成编码</Button>
                      </Row>
                    </FormItem>
                    <!-- </Row> -->

                    <!-- </FormItem> -->
                  </div>
                </td>
              </tr>

              <tr class="ivu-table-row">
                <td></td>
                <td></td>
              </tr>

              <tr v-if="formData.snCodeList.length" class="ivu-table-row">
                <td colspan="2">
                  <div class="ivu-table-cell">
                    <h3 class="title"><span class="title-icon"></span> <span>SN列表</span></h3>
                  </div>
                </td>
              </tr>
              <tr v-for="(item, index) in formData.snCodeList" :key="index" class="ivu-table-row">
                <td colspan="2">
                  <div class="ivu-table-cell">
                    <FormItem :label="`产品编码${String(index + 1).padStart(3, '0')}：`">
                      <Input disabled :value="item" class="input-width" placeholder="自动根据编码信息生成" />
                    </FormItem>
                  </div>
                </td>
              </tr>
              <tr class="ivu-table-row">
                <td colspan="2">
                  <div class="ivu-table-cell">
                    <FormItem>
                      <Button :disabled="!formData.snCodeList.length" style="width: 100px; margin-right: 20px;" @click="handleSubmit" type="primary"
                        >确认</Button
                      >
                      <Button @click="handleCancle" style="width: 100px;">取消</Button>
                    </FormItem>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </Form>
    <!-- pn生成器 -->
  </div>
</template>
<script>
import { machineList, snGet, snSave } from '@/api/asset/repair/asset-manage'
import dayjs from 'dayjs'
import { blobToXls } from '@/libs/blobToXls'
import { cloneObj } from '@/libs/cloneObj'
import { routeEqual } from '@/libs/util'
const PURCHASETYPE = {
  1: 'P',
  2: 'R',
  3: 'T'
}
export default {
  name: 'makersn',
  data () {
    return {
      uploadList: [],
      formData: {
        purchaseType: '',
        pnCode: '',
        purchaseAmount: '',
        fileName: 'SN.xlsx',
        purchaseTime: '',
        merchantId: this.$store.state.user.merchantId,
        snCodeList: []
      },
      copyData: {}, // 复制一份数据
      timer: null,
      loading: false,
      pnCodeData: [],
      purchaseTypeData: [
        { label: '新购', value: '1' },
        { label: '合作', value: '2' },
        { label: '试用', value: '3' }
      ],
      purchaseAmountData: [],
      formRule: {
        purchaseTime: [{ required: true, message: '请选择采购时间' }],
        purchaseType: [{ required: true, message: '请选择采购类型' }],
        pnCode: [{ required: true, message: '请选择机台产品' }],
        purchaseAmount: [{ required: true, message: '请选择采购数量' }]
      },
      // 物理信息
      physics: [
        { key: 'machineCategoryName', label: '功率', placeholder: '输入6位数字，单位瓦' },
        { key: 'machineCategoryName', label: '净重', placeholder: '输入小数点前6位及后2位，单位公斤' },
        { key: 'machineCategoryName', label: '长', placeholder: '输入6位数字，单位毫米' },
        { key: 'machineCategoryName', label: '宽', placeholder: '输入6位数字，单位毫米' },
        { key: 'machineCategoryName', label: '高', placeholder: '输入6位数字，单位毫米' },
        { key: 'machineCategoryName', label: '文化审批号', placeholder: '请输入' }
      ]
    }
  },
  created () {
    this.purchaseAmountData = Array.from(new Array(999).keys(), x => {
      return { value: x + 1, label: x + 1 }
    })
  },
  methods: {
    // 远程搜索
    async handleRemoteMethod (query) {
      if (this.timer) clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        this.loading = true
        const res = await machineList({ name: query })
        this.loading = false
        if (res.data.status !== 200) return this.$Message.error(res.data.error)
        this.pnCodeData = res.data.data || []
      }, 500)
      // console.log(query)
    },
    // 生成编码
    async handleGenerateCode () {
      this.$refs.formValidate.validate(async valid => {
        if (!valid) return null
        const { pnCode, merchantId, purchaseAmount, purchaseTime, purchaseType } = this.formData
        // let formData = new FormData()
        // formData.append('pnCode', pnCode)
        // formData.append('merchantId', merchantId)
        const res = await snGet({ pnCode, merchantId, purchaseAmount })
        if (res.data.status !== 200) return this.$Message.error(res.data.error)
        this.formData.snCodeList = Array.from(new Array(purchaseAmount - 0).keys(), x => {
          let no = `${x + res.data.data}`.padStart(3, '0')
          return `${PURCHASETYPE[purchaseType]}${pnCode.slice(0, 6)}${dayjs(purchaseTime)
            .format('YY-MM')
            .replace('-', '')}${no}`
        })
        this.copyData = cloneObj(this.formData)
      })
    },
    // 提交表单
    async handleSubmit () {
      this.$refs.formValidate.validate(async valid => {
        if (!valid) return null
        let change = false
        Object.keys(this.formData).filter(key => key !== 'snCodeList').map(key => {
          if (key === 'purchaseTime') {
            if (!dayjs(this.formData[key]).isSame(dayjs(this.copyData[key]))) {
              change = true
            }
          } else {
            if (this.formData[key] !== this.copyData[key]) {
              change = true
            }
          }
        })
        if (change) {
          this.$Modal.warning({
            title: '温馨提示',
            content: '数据发生变化，请点击生成编码按钮重新生成产品编码'
          })
          return null
        }
        let { purchaseTime } = this.formData
        purchaseTime = dayjs(purchaseTime)
          .format('YYYY-MM')
          .replace('-', '')
        const res = await snSave({ ...this.formData, purchaseTime })
        console.log(res.status)
        if (res.status === 200) this.$Message.success('提交成功')
        // this.$Message.success('提交成功');
        blobToXls(res.data, `SN列表${dayjs().format('YYYY-MM-DD HH:mm:ss')}`)
        // if (res.data.status !== 200) return this.$Message.error(res.data.error)
      })
    },
    // 点击去取消
    handleCancle () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit(
        'setTagNavList',
        this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item))
      )
    }
  }
}
</script>
<style lang="less" scoped>
.asset-manage-makerpn {
  margin: 0 auto;
  padding: 40px 80px;
  .asset-manage-makerpn-info {
    margin: 0 auto;
    max-width: 900px;
  }
  .title {
    display: flex;
    align-items: center;
  }
  .title-icon {
    display: inline-block;
    height: 20px;
    width: 8px;
    background: #2d8cf0;
    margin-right: 10px;
  }

  .upload-list {
    display: inline-block;
    width: 96px;
    height: 96px;
    text-align: center;
    line-height: 96px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
  }
  .upload-list img {
    width: 100%;
    height: 100%;
  }
  .upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
    color: #fff;
  }
  .upload-list:hover .upload-list-cover {
    display: block;
  }
  .supload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }

  .input-width {
    width: 260px;
  }

  .ivu-table-noborder td {
    border-bottom: none;
  }
  .ivu-table-noborder:before {
    content: '';
    width: 100%;
    height: 0px;
  }
  .ivu-table-noborder:after {
    content: '';
    width: 100%;
    height: 0px;
  }
  .ivu-table-border th,
  .ivu-table-border td {
    border-bottom: 1px solid #e8eaec;
  }
}
</style>
